#include <vector>
#include <map>
#include <string>
#include <iostream>
#include "word.hpp"
#include "strlib.hpp"

using namespace std;

Word::Word(string line, bool print) {
  this->timesTested = 0;
  this->score = 0;
  this->percentage = 1;
  auto byLangs = split(line, "; ");
  if(print) {
    cout << "Generating from line: " << line << "\n"; 
  }
  for(int i = 0; i < byLangs.size(); i++) {
    auto langAndWord = split(byLangs[i], " -> ");
    this->words[langAndWord[0]] = split(langAndWord[1], ", ");
    if(print) {
      cout << langAndWord[0] << " words: " << this->getByLang(langAndWord[0]) << "\n";
    }
  }
}

float Word::checkByLang(string language, string answer) {
  float max = 0;
  for(int i = 0; i < this->words[language].size(); i++) {
    float current = compareStrings(this->words[language][i], answer);
    if(current > max) {
      max = current;
    }
  }
  return max;
}

string Word::getByLang(string language) {
  string result;
  for(int i = 0; i < this->words[language].size(); i++) {
    result.append(this->words[language][i]);
    if(i != this->words[language].size() -1) {
      result.append(", ");
    }
  }
  return result;
}

float Word::testByLang(string language1, string language2) {
  string answer;
  cout << this->getByLang(language1) << " " << language1 << " -> " << language2 << " ";
  getline(cin, answer);
  this->timesTested++;
  float currentScore = this->checkByLang(language2, answer);
  this->score += currentScore;
  this->percentage = (float)this->score / (float)this->timesTested;
  cout << currentScore * 100 << "% Correct";
  if (currentScore < 0.8) {
    cout << ", answers: " << this->getByLang(language2);
  }
  cout << "\n";
  return currentScore;
}

void sortByScore(vector<Word*>* wordList, bool fromBest) {
  vector<int> sortedIndexes;
  vector<Word*> result;
  for(int i = 0; i < wordList->size(); i++) {
    int worst = 9999;
    for(int e = 0; e < wordList->size(); i++) {
      if((*wordList)[e]->percentage < worst) {
        for(int p = 0; p < sortedIndexes.size(); p++) {
          if(sortedIndexes[p] == e) {
            goto innerLoopEnd;
          }
        }
        sortedIndexes.push_back(e);
        goto outerLoopEnd;
      }
    innerLoopEnd:;
    }
  outerLoopEnd:;
  }
  for(int i = 0; i < sortedIndexes.size(); i++) {
    result.push_back((*wordList)[sortedIndexes[i]]);
  }
  (*wordList) = result;
}
